//
//  PersonInfoViewController.m
//  citzenWorkStation
//
//  Created by yang qing on 2018/2/28.
//  Copyright © 2018年 yang qing. All rights reserved.
//

#import "PersonInfoViewController.h"
#import "UIColor+Hex.h"
#import "UserInfoBean.h"
#import "DataSaveUtils.h"
#import "CommonReqManage.h"
#import "AFNetworking.h"
#import "API.h"
#import "NSObject+YYModel.h"
#import <SDWebImage/UIImageView+WebCache.h>
@interface PersonInfoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *maginTop;

@property (weak, nonatomic) IBOutlet UIImageView *ivHeadImage;
@property (weak, nonatomic) IBOutlet UIButton *btnSubmit;
@property (weak, nonatomic) IBOutlet UITextField *tfNickName;
@property (weak, nonatomic) IBOutlet UILabel *labName;
@property (weak, nonatomic) IBOutlet UILabel *labSex;
@property (weak, nonatomic) IBOutlet UILabel *labID;
@property (strong,nonatomic) NSMutableArray *imgArray;
@property (strong,nonatomic) UserInfoBean *userInfo;
@property (copy,nonatomic) UIImage *selectImage;//从相册或者相机选中的图片
@end

@implementation PersonInfoViewController
UIImagePickerController *imagePicker;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self getImgPath];
    
    //获取状态栏的高度进行适配iponeX
    // 状态栏(statusbar)
    CGRect StatusRect = [[UIApplication sharedApplication] statusBarFrame];
    //标题栏
    CGRect NavRect = self.navigationController.navigationBar.frame;
    _maginTop.constant = StatusRect.size.height + NavRect.size.height;

    
    _ivHeadImage.userInteractionEnabled = YES;
     [_ivHeadImage addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headClick)]];
    [_btnSubmit addTarget:self action:@selector(submitClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)initView{
    [self initNav];
    self.tfNickName.textAlignment = NSTextAlignmentRight;
    //设置图片圆角
    _ivHeadImage.layer.cornerRadius = _ivHeadImage.frame.size.width/2.0;
    _ivHeadImage.layer.masksToBounds = YES;
    
    //展示信息
    self.userInfo = [DataSaveUtils getUserInfo];
    [self showUserInfo:self.userInfo];
    
}

- (void)submitClick{
    [self.userInfo setNickname:_tfNickName.text];
    [self showHub:@""];
    if(self.selectImage){
        [self uploadImag:self.selectImage];
    }else{
        [self uploadData];
    }
}


- (void)uploadImag:(UIImage *)image{
    //4. 发起网络请求
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7f);
    [CommonReqManage uploadHeadImg:imageData fileName:self.imgArray[0] fileType:@"image/jpeg" imagePath:self.imgArray[0] progress:^(NSInteger percent) {
        NSLog(@"upload---%ld",percent);
    } success:^(id success) {
        //上传成功时的回调
        NSString *status =  success[@"status"];
        if([status isEqualToString:@"1"]){
//            [self showToast:@"上传成功"];
            [self.userInfo setHeadImgUrl:self.imgArray[0]];
            [self uploadData];
        }else{
             [self showTip:success[@"message"] cancelText:@"" confirmText:@"确定" Confirm:nil Cancel:nil];
            [self hiddenHub];
        }
    } failed:^(id failure) {
        //失败时的回调
         [self hiddenHub];
        [self showToast:@"上传图失败"];
    }];
}
- (void)uploadData{
    id userInfoJSON = [self.userInfo yy_modelToJSONObject];
    [CommonReqManage updateUserInfo:userInfoJSON success:^(id success) {
         [self hiddenHub];
        NSString *status =  success[@"status"];
        if([status isEqualToString:@"1"]){
            [DataSaveUtils saveUserInfo:self.userInfo];
            [self showToast:@"修改成功"];
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        }else{
            [self showTip:success[@"errMsg"] cancelText:@"" confirmText:@"确定" Confirm:nil Cancel:nil];
        }
    } failed:^(id faiure) {
        NSLog(@"failure");
         [self hiddenHub];
        [self showHubAuto:@"请求失败"];
    }];
}

- (void)getImgPath{
    self.imgArray = [[NSMutableArray alloc]init];
    [CommonReqManage getFilePath:1 fileType:@"image" suffix:@"jpeg" success:^(id success) {
        self.imgArray = success;
    } failed:^(id failure) {
        [self showToast:@"图片路径获取失败，暂时不能上传照片"];
    }];
}

- (void)headClick{
    UIAlertController *photoSheet = nil;
      photoSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickImageFromCaram];
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickImageFromAlbum];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [photoSheet addAction:takePhotoAction];
        [photoSheet addAction:albumAction];
        [photoSheet addAction:cancelAction];
        
    }else {
//        [photoSheet addAction:takePhotoAction];
        [photoSheet addAction:albumAction];
        [photoSheet addAction:cancelAction];
    }
    [self presentViewController:photoSheet animated:YES completion:nil];
   
}
- (void)pickImageFromAlbum
{
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate =self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing =YES;
    [self presentViewController:imagePicker animated:YES completion:nil];
}


- (void)pickImageFromCaram
{
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate =self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing =YES;
    [self presentViewController:imagePicker animated:YES completion:nil];
}


- (void)showUserInfo:(UserInfoBean *)useInfo{
    if(useInfo){
        if(useInfo.nickname){
            _tfNickName.text = useInfo.nickname;
        }
        if(useInfo.sex == 1){
            _labSex.text =@"男";
        }else{
            _labSex.text =@"女";
        }
        if(useInfo.auth == 1){
            _labID.text = useInfo.identitynumber;
            _labName.text = useInfo.name;
            
        }else if(useInfo.auth == 3){
            _labID.text = @"实名认证审核中";
            _labName.text = @"实名认证审核中";
            
        }else{
            _labID.text = @"未实名认证";
            _labName.text = @"未实名认证";
            _labSex.text=@"未实名认证";
        }
        //展示头像
        NSString *baseImgeUrl = [FILE_BASE_URL stringByAppendingString:@"/get"];
        NSString *headImageUrl = [baseImgeUrl stringByAppendingString:useInfo.headImgUrl];
        [_ivHeadImage sd_setImageWithURL:[NSURL URLWithString:headImageUrl]
                        placeholderImage:[UIImage imageNamed:@"icon_default_avatar"]];
    }
}



- (void)initNav{
    self.navigationController.navigationBar.barTintColor =
    [UIColor colorWithHexString:ThemeColor];
    //设置导航栏标题文字和文字大小
    [self setNavtitle:@"个人信息"];
    //设置两侧按钮
    [self setNavLeftImg:@"nav_back"];
}


- (void)backClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        NSString *key = nil;
        if (picker.allowsEditing){
            key = UIImagePickerControllerEditedImage;//编辑后的图片
        }else{
            key = UIImagePickerControllerOriginalImage;//原始图片，相册或刚拍完照的图片
        }
        UIImage *imageNew = [info objectForKey:key];
        //设置image的尺寸
        CGSize imagesize = imageNew.size;
        imagesize.height =60;
        imagesize.width =60;
        //对图片大小进行压缩--
        imageNew = [self imageWithImage:imageNew scaledToSize:imagesize];
        
        self.selectImage = imageNew;
        [self.ivHeadImage setImage:imageNew];
//        [self uploadImag:imageNew];
    }else{
        [self showToast:@"请选择图片类型"];
    } 
    [picker dismissViewControllerAnimated:YES completion:nil];
}




//对图片尺寸进行压缩--
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}
@end
